import React, {Component} from 'react';
import {inject, observer} from 'mobx-react';
import * as mobx from 'mobx';
import {Tree, Button, Modal, Spin} from 'antd';
import {WeaScroll, WeaDialog, WeaTree, WeaLocaleProvider} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
require('../../style/tree.less');

@inject("favouriteBrowserStore", "favouriteDialogStore", "sysFavouriteStore")
@observer
export default class FavouriteBrowser extends Component {
    constructor(props) {
        super(props);
    }


    /**
     * 树节点选中
     * @param key
     * @param evt
     */
    onSelect = (key, evt) => {
        const {favouriteBrowserStore} = this.props;
        let dirId = '0'; // 默认是根目录
        if (key.length > 0) {
            dirId = key[0];
        }

        if (dirId.indexOf('add') == -1 && dirId.indexOf('edit') == -1) { // 非编辑状态下
            /**
             * 记录下选中的节点
             */
            favouriteBrowserStore.selectTreeNode(dirId);
        }
    }

    /**
     * 保存目录
     * @param evt
     */
    saveFavourite = (evt) => {
        const {favouriteBrowserStore} = this.props;
        const {selectedKey} = favouriteBrowserStore;
        for (const key in this.refs) {
            const inputObj = this.refs[key];
            const value = inputObj.value;
            if (!value) { // 值为空
                Modal.error({content: `${getLabel(388203, '目录名称不能为空！')}`});
                inputObj.focus();
            } else {
                const parentid = selectedKey;
                const favname = value;
                const favdesc = '';
                const favorder = 0;
                favouriteBrowserStore.saveTreeNode({parentid, favname, favdesc, favorder});
            }
            break;
        }
    }

    /**
     * 编辑框的回车事件处理
     * @param evt
     */
    handleOnKeyDown = (evt) => {
        const keyCode = evt.keyCode;
        if (keyCode == 13) { // enter key
            this.saveFavourite(evt);
        }
    }

    /**
     * 关闭窗口
     */
    closeBrowserWin = () => {
        const {favouriteDialogStore, favouriteBrowserStore} = this.props;
        favouriteDialogStore.closeBrowserDialog();
    }

    /**
     * 保存数据
     * @param evt
     */
    submitBrowserWin = (evt) => {
        const {sysFavouriteStore, favouriteBrowserStore} = this.props;
        const {selectedKey} = favouriteBrowserStore;
        let {moveids} = sysFavouriteStore;
        moveids = mobx.toJS(moveids);
        if (!selectedKey) { // 没有选中目录
            Modal.error({
                content: `${getLabel(385877, '请选择一个目录！')}`,
            });
        } else {
            sysFavouriteStore.moveToAnotherDir(moveids.join(), selectedKey);
        }
    }


    onRadioCheck = (checkedId) => {
        const {favouriteBrowserStore} = this.props;
        if (checkedId.indexOf('add') == -1 && checkedId.indexOf('edit') == -1) { // 非编辑状态下
            /**
             * 记录下选中的节点
             */
            favouriteBrowserStore.selectTreeNode(checkedId);
        }
    }

    componentDidUpdate() {
        /**
         * 默认选中文本框
         */
        for (const key in this.refs) {
            this.refs[key].focus();
            break;
        }
    }

    asyncLoad = (item) => { // 这里可以优化
        const nodeid = item.nodeid;
        const {favouriteBrowserStore} = this.props;

        function fn() {
            return new Promise((resolve, reject) => {
                resolve(favouriteBrowserStore.loadTreedata(nodeid)); // 这是一个异步函数
            });
        }

        const fn_1 = async function () {
            const data = await fn();// 等待异步操作执行完了后执行的方法
            return new Promise((resolve) => { // loadData接口需要一个promise对象，所以这里要包装返回一个promise对象
                const data = {
                    datas: mobx.toJS(favouriteBrowserStore.testchildrendata),
                };
                resolve(data);
            });
        };
        return fn_1();
    }

    onTreeRadioCheck = (id, radioCheckedKey) => {
        const {favouriteBrowserStore} = this.props;
        favouriteBrowserStore.selectedKey = radioCheckedKey;
    }

    render() {
        /**
         * 移动时，打开的收藏目录窗口信息
         */
        const {favouriteDialogStore, favouriteBrowserStore} = this.props;
        const visible = favouriteDialogStore.showBrowserDialog;
        const title = `${getLabel(388236, '收藏目录')}`;
        const style = {width: 620, height: 500};
        const buttons = [
            (
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yjxkrq@submit`}
                        onClick={this.submitBrowserWin}>
                    {getLabel('826', '确定')}
                </Button>
            ),
            (
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qbi1b6@close`}
                        onClick={this.closeBrowserWin}>
                    {getLabel('31129', '取消')}
                </Button>
            ),
        ];
        const onCancel = this.closeBrowserWin;
        const params = {visible, title, style, buttons, onCancel};
        const {treeData, selectedKey, spinning, tip} = favouriteBrowserStore;

        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@d1ku48`} {...params}>
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@sdjot5`}
                      spinning={spinning}
                      tip={tip}
                      size="large">
                    <div className="favourite-browser-container">
                        <WeaScroll
                            ecId={`${this && this.props && this.props.ecId || ''}_WeaScroll@z1z7s1`}
                            className="sysfav-scroll-wrapper"
                            typeClass="scrollbar-macosx"
                            style={{width: '100%'}}
                        >
                            <div className="favourite-browser-content">
                                <WeaTree
                                    ecId={`${this && this.props && this.props.ecId || ''}_WeaTree@hspwiv`}
                                    hasRadio
                                    radioCheckedKey={favouriteBrowserStore.selectedKey}
                                    onRadioCheck={this.onTreeRadioCheck}
                                    datas={mobx.toJS(favouriteBrowserStore.testfatherdata)}
                                    loadData={this.asyncLoad}
                                />
                            </div>
                        </WeaScroll>
                    </div>
                </Spin>
            </WeaDialog>
        );
    }
}

